import request from '../../utils/http';

//声明 reducer 函数
let init = [];
/**
 * 新增  {type: 'ADD_TODO', payload: {title: '搬家', done: false, id: 'xxxdsa'}}
 * 更新  {type: 'CHECK_TODO', payload: {id: 1, done: true}}
 * 删除  {type: 'REMOVE_TODO', payload: 1}
 * 批量更新  {type: 'CHECK_ALL_TODO', payload: true}
 * 批量删除  {type: 'REMOVE_DONE_TODOS'}
 * 设置状态 {type: 'INIT_TODO', payload: [{id: 1, title:'xx'}, {id: 2, title: 'xx'}]}
 */
let todoReducer = (state=init, action) => {
  //根据 action.type 进行状态的更新
  switch(action.type){
    case 'ADD_TODO':
      return [...state, action.payload];
    case 'CHECK_TODO':
      return state.map(item => {
        //判断
        if(item.id === action.payload.id){
          //更新完成状态
          item.done = action.payload.done;
        }
        return item;
      })
    case 'REMOVE_TODO':
      return state.filter(item => item.id !== action.payload);
    case 'CHECK_ALL_TODO':
      return state.map(item => {
        item.done = action.payload;
        return item;
      })
    case 'REMOVE_DONE_TODOS':
      return state.filter(item => !item.done);
    case 'INIT_TODO':
      return action.payload;
    default: 
      return state;
  }
};

//暴露 reducer
export default todoReducer;

//新增任务的 action creator
export let addTodoAction = payload => ({type: 'ADD_TODO', payload: payload});
export let checkTodoAction = payload => ({type: 'CHECK_TODO', payload: payload});
export let removeTodoAction = id => ({type: 'REMOVE_TODO', payload: id})
export let checkAllTodoAction = done => ({type: 'CHECK_ALL_TODO', payload: done});
export let removeDoneTodosAction = () => ({type: 'REMOVE_DONE_TODOS'});
export let initTodoAction = payload => ({type: 'INIT_TODO', payload: payload})

//声明异步的 action creator
export function asyncGetTodosAction(){
  return async dispatch => {
    //获取任务数据
    let result = await request.get('/todos');
    //更新 redux 中的 todo 状态
    dispatch(initTodoAction(result));
  } 
}

//发送请求新增任务
export function asyncAddTodoAction(title){
  return async dispatch => {
    //发送请求新增任务
    let result = await request.post('/todos', {title: title, done: false});
    //更新状态
    dispatch(addTodoAction(result));
  }
}

//发送请求更新任务的完成状态
export function asyncCheckTodoAction(id, done){
  return async dispatch => {
    //发送请求
    await request.patch(`/todos/${id}`, {done: done})
    //更新 redux 中的状态
    dispatch(checkTodoAction({id: id, done: done}));
  }
}

//发送请求删除某个任务
export function asyncRemoveTodoAction(id){
  return async dispatch => {
    await request.delete(`/todos/${id}`);
    //更新 redux 中的状态
    dispatch(removeTodoAction(id));
  }
}